#!/usr/bin/env python
#
# StocksDB.py
# Copyright (C) 2011 Piotr Foltyn
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import AutoLock
import CommandThread
from Secret import *
import threading
import pymysql


class AddTransactionCommand(CommandThread.Command):
    isin     = None
    datetime = None
    open     = None
    high     = None
    low      = None
    close    = None
    volume   = None

    def execute(self, cursor):
        cursor.execute('SELECT `stockId` FROM `Symbols` WHERE `isin`=%s;', self.isin)
        cursor.execute(
            'INSERT INTO `Quotes` (`stockId`, `datetime`, `open`, `high`, `low`, `close`, `volume`) VALUES (%s, %s, %s, %s, %s, %s, %s);', 
            (cursor.fetchone()[0], self.datetime, self.open, self.high, self.low, self.close, self.volume)
        )


class GetAllIsinsCommand(CommandThread.Command):
    isins = []

    def execute(self, cursor):
        cursor.execute('SELECT `isin` FROM `Symbols`;')
        for isin in cursor.fetchall():
            self.isins.append(str(isin[0]))


# Do not instantiate this class, use GetDB() below
class _StocksDB(CommandThread.CommandThread):
    def __init__(self):
        super(_StocksDB, self).__init__()

    def _handleCommand(self, command):
        connection = pymysql.connect(host=ZGJIb3N0, port=3306, user=ZGJVc2Vy, passwd=ZGJQYXNzd29yZA, db=ZGJOYW1l)

        cursor = connection.cursor()
        command.execute(cursor)
        command.taskDone()
        cursor.close()

        connection.commit()
        connection.close()


_dbAccessLock = threading.Lock()
_stockDB = None


def GetDB():
    global _dbAccessLock
    with AutoLock.AutoLock(_dbAccessLock) as lock:
        global _stockDB
        if None == _stockDB:
            _stockDB = _StocksDB()
            _stockDB.start()
        return _stockDB
